import { createRouter, createWebHashHistory } from "vue-router";
import baseRoutes from "./baseRoutes";
import { useDict } from "@/stores/dictStore"
import { useUser } from "@/stores/user"
import { getToken, setToken } from "@/utils/auth"
export const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login.vue"),
    meta: {
      title: "登录",
      index: 1,
    },
  },
  {
    path: "/:catchAll(.*)",
    // name: "NotFound",//不能有，4.0以上不需要手动push404页面，直接这里这样配置404
    meta: {
      title: "NotFound",
    },
    component: () => import("@/views/404.vue"),
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...baseRoutes['routes'], ...routes],
});
export function resetRouter() {
  const newRouter = createRouter({
    history: createWebHashHistory(),
    routes: routes,
  });
  router.matcher = newRouter.matcher; // reset router
}
// 路由白名单
const whiteList = ["/login"];
let isFirstEnter = true
function getUrlParams() {
  var url = window.location.href
  let paramsObj = new Object()
  if (url.indexOf('?') !== -1) {
    var a = url.split('?')[1]
    var str = a.split('&')
    for (let i = 0; i < str.length; i++) {
      paramsObj[str[i].split('=')[0]] = decodeURI(str[i].split('=')[1])
    }
  }
  return paramsObj
}
router.beforeEach(async (to, from, next) => {
  if (getUrlParams().token) {
    setToken(getUrlParams().token)
  }
  const token = getToken()
  if (token) {
    if (to.path == '/login') {
      next({ path: '/' })
    }
    if (isFirstEnter) {
      const dictStore = useDict()
      await dictStore.initDict()
      const userStore = useUser()
      await userStore.getInfo()
    }
    isFirstEnter = false
    next()
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // 如果这个页面不在白名单里，直接跳转到登录页面
      next('/login');
    }
  }
});

export default router;
